package com.rxyb.security.service.impl;

import cn.hutool.json.JSONUtil;
import cn.rxyb.core.respone.R;
import cn.rxyb.core.respone.enums.CommonCode;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rxyb.security.db.po.SysUser;
import com.rxyb.security.db.dao.SysUserMapper;
import com.rxyb.security.gate.model.*;
import com.rxyb.security.gate.model.common.AddSysUserReq;
import com.rxyb.security.gate.model.common.AddSysUserRsp;
import com.rxyb.security.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxyb.security.service.logic.SysUserLogic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author YJH
 * @since 2020-07-07
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserLogic sysUserLogic;

    public SysUserServiceImpl(SysUserLogic sysUserLogic) {
        this.sysUserLogic = sysUserLogic;
    }

    @Override
    public R<AddSysUserRsp> addSysUser(AddSysUserReq req, AddSysUserRsp rsp) {
        log.info("sysUserService --> addSysUser 请求参数:[{}]", JSONUtil.toJsonStr(req));
        SysUser user = new SysUser();
        BeanUtils.copyProperties(req, user);
        user.setPassword(new BCryptPasswordEncoder().encode("123456")); // 默认密码
        return sysUserLogic.add(user) ? R.ok(rsp) : R.failed(CommonCode.DB_ERROR);
    }

    @Override
    public R<UpdateSysUserRsp> updateSysUser(UpdateSysUserReq req, UpdateSysUserRsp rsp) {
        log.info("sysUserService --> updateSysUser 请求参数:[{}]", JSONUtil.toJsonStr(req));
        SysUser user = new SysUser();
        BeanUtils.copyProperties(req, user);
        return sysUserLogic.update(user) ? R.ok(rsp) : R.failed(CommonCode.DB_ERROR);
    }

    @Override
    public R<UserListRsp> userList(UserListReq req, UserListRsp rsp) {
        log.info("sysUserService --> userList 请求参数:[{}]", JSONUtil.toJsonStr(req));
        SysUser user = new SysUser();
        BeanUtils.copyProperties(req, user);
        IPage<SysUser> userPage = sysUserLogic.findUserPage(user, req);
        log.info("sysUserService --> userResponse [{}]" + JSONUtil.toJsonStr(userPage));
        rsp.setTotalCount(userPage.getTotal());
        rsp.setTotalPages(userPage.getPages());
        rsp.setBeans(userPage.getRecords().stream().map(e -> sysUserLogic.dbToModel(e)).collect(Collectors.toList()));
        return R.ok(rsp);
    }
}
